package com.qingxin.sys.verifier;

import java.io.File;
import java.util.Hashtable;
import java.util.Map;

import com.qingxin.sys.support.UploadFile;

/**
 * 表单验证工厂方法<br>
 * <br>
 * 表单验证原则：<br>
 * 1.在前台进行强验证：只要后台验证不通过就认定为恶意请求，此时不应向请求者返回详细错误信息。<br>
 * 2.在前台进行弱验证：在验证不通过时需要向前台返回详细错误信息。<br>
 * @author Administrator
 *
 */
public final class FormFactory {
	
	private static final Map<String, Form> FORM_MAP = new Hashtable<>();
	
	
	/**
	 * 获取表单配置
	 * 
	 * @param formAction 表单URI，可使用request.getServletPath()获得
	 * @return
	 */
	public static Form getForm(String formAction) {
//		Form form = null;
//		synchronized (FORM_MAP) {
//			form = FORM_MAP.get(formAction);
//			if(form == null){
//				try {
//					String baseDir = UploadFile.getRealpath("/WEB-INF/verifiers/");
//					File file = new File(baseDir, formAction+".xml");
//					if(file.isFile()){
//						XMLDigester digester = new XMLDigester(FormFactory.class.getResource("form.rule.xml"));
//						form = (Form) digester.parse(file);
//					}
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//				if(form != null){
//					FORM_MAP.put(formAction, form);
//				}
//			}
//		}
//		return form;
		try {
			String baseDir = UploadFile.getRealpath("/WEB-INF/verifiers/");
			File file = new File(baseDir, formAction+".xml");
			if(file.isFile()){
				XMLDigester digester = new XMLDigester(FormFactory.class.getResource("form.rule.xml"));
				return (Form) digester.parse(file);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	/**
	 * 清空缓存
	 */
	public static void clear(){
		synchronized (FORM_MAP) {
			FORM_MAP.clear();
		}
	}
	
	
}
